package org.javaboy.sms_login.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.session.HttpSessionEventPublisher;

/**
 * Map<User,List<SessionInformation>>
 */
@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(a -> a.anyRequest().authenticated())
                .formLogin(Customizer.withDefaults())
                .csrf(c -> c.disable())
                //ConcurrentSessionFilter
                .sessionManagement(s ->
                                s.sessionFixation(f -> f.changeSessionId())
                                        //设置会话的最大并发数，即同一个用户最多只能登录一个设备
                                        .maximumSessions(1)
                                        //当会话过期之后，自动跳转到这个地址，默认是展示一段文本
//                                .expiredUrl("")
                                        //当达到最大并发数的时候，禁止登录
                                        .maxSessionsPreventsLogin(true)
                );
        return http.build();
    }

    @Bean
    HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }
}
